package com.ldf.jrtsp.handler;

import cn.hutool.core.util.StrUtil;
import com.ldf.jrtsp.enums.MediaType;
import com.ldf.jrtsp.enums.RtspAuthType;
import com.ldf.jrtsp.parser.RtspDataParser;
import com.ldf.jrtsp.parser.RtspSdpParser;
import com.ldf.jrtsp.player.RtspPlayer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.ldf.jrtsp.constants.RtspConstants.*;
import static com.ldf.jrtsp.enums.RtspOptionsType.DESCRIBE;

/**
 * describe reply handle
 *
 * @author lidaofu
 * @since 2024/6/19
 **/
public class RtspDescribeReplyHandle implements RtspReplyHandle {
    private final static Logger log = LoggerFactory.getLogger(RtspDescribeReplyHandle.class);

    @Override
    public void handle(RtspPlayer player,RtspDataParser rtspDataParser) {
        if (rtspDataParser.getResponse().equals(RTSP_OK)) {
            String uri = rtspDataParser.getHeaders().get(RTSP_CONTENT_BASE);
            if (StrUtil.isNotBlank(uri)) {
                player.setContentBase(uri);
            }
            if (StrUtil.isNotBlank(rtspDataParser.getSdp())) {
                RtspSdpParser rtspSdpParser = new RtspSdpParser(rtspDataParser.getSdp());
                player.setRtspSdp(rtspSdpParser);
                MediaType[] mediaTypes = rtspSdpParser.getMediaTypes();
                for (MediaType mediaType : mediaTypes) {
                    if (mediaType != null) {
                        player.sendSetup(mediaType);
                    }
                }
                player.sendVersionData();
                player.sendPlay();
            } else {
                log.warn("sdp is empty");
            }
        } else if (rtspDataParser.getResponse().equals(RTSP_UNAUTHORIZED)) {
            String authInfo = rtspDataParser.getHeaders().get(RTSP_AUTH_HEARD);
            RtspAuthType respAuthType = RtspAuthType.getRespAuthType(authInfo);
            player.setRtspAuthType(respAuthType);
            player.sendDescribe(authInfo);
            log.info("rtsp auth type is {}", respAuthType.getValue());
        } else {
            log.warn("rtsp describe reply is {}", rtspDataParser.getResponse());
        }
        player.sendOptionsCallBack(DESCRIBE,rtspDataParser);
    }
}
